<?php
include '../template.php';
include '../dbconfig/config.php';
include '../dbconfig/opendb.php';
include './peptideformat.php';
include '../util/dbutil.php';
getTopWithJS("..");
?>

&nbsp;<br />

<?php
function merge_params($params) {
    if (count($params)<=1)
        return $params;

    $keep[] = array();
    $n = count($params);
    for ($i=0; $i<$n; $i++) {
        $parami = $params[$i];
        $keep[$i] = true;
        for ($j=0; $j<$i; $j++) {
            if ($keep[$j]) {
                $paramj = $params[$j];
                // find the intersection of two arrays
                $intersect = array_intersect_assoc($parami,$paramj);
                // if the new param is equal or contained in an existing param
                if (count($intersect)==count($parami)) {
                    $keep[$i] = false;
                    break;
                } elseif (count($intersect)==count($paramj)) {
                    // if the existing param is contained in the new param
                    $keep[$j] = false;
                    break;
                }
            }
        }
    }

    $ret = array();
    for ($i=0; $i<$n; $i++) {
        if ($keep[$i]) {
            $ret[] = $params[$i];
        }
    }

    return $ret;
}

        $queryDs = "SELECT reference,dataSource.id FROM peptide,mass,dataSource WHERE peptide.mass=mass.id AND mass.dataSource=dataSource.id AND ";
        $query = "SELECT peptide.id,peptide.location,peptide.sequence,mass.id as msid,mass.file,mass.scan,ISNULL(mass.mz) AS nullMass,dataSource.reference,dataSource.link,protein.id AS pid,protein.annotation,organism.latin,organism.commonName ".
                 "FROM peptide,mass,dataSource,protein,organism ".
                 "WHERE peptide.mass=mass.id AND peptide.protein=protein.id AND mass.dataSource=dataSource.id AND protein.organism=organism.label AND ";
	if(isset($_GET['id'])) {
//            $ids = array_unique(explode(",",$_GET['id']));
//            $q = "peptide.id IN (".implode(",", $ids).")";
            $q= "peptide.id={$_GET['id']}";
            $query .= $q;
            $queryDs .= $q;
	} elseif (isset($_GET['pnrseq'])) {
            $pseq = $_GET['pnrseq'];
            $pro = $_GET['pro'];
            $loc = $_GET['loc'];
            $q = "peptide.phosphoSequence='$pseq' AND peptide.protein=$pro AND peptide.location=$loc";
            $query .= $q;
            $queryDs .= $q;
        } else {
            die('Phosphosite information not available!');
        }

        $getref = "";
        $ref = $_GET['ref'];
        if (!empty($ref)) {
            $q = " AND mass.dataSource=$ref";
            $query .= $q;
            $getref = "ref=$ref";
        }

        $query .= " ORDER BY mass.id";

        $result = mysql_query($query) or die("Error, query failed--$query");
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        if ($row) {
            $seqpep = $row['sequence'];
            $seq = formatpep_unlink($seqpep,$row['id'],".",$getref);
            $orghtml = "{$row['latin']}</i> ({$row['commonName']})";
            $loc = $row['location'];
            $prohtml = "<a href=\"protein.php?id=".$row['pid'].$getref."\">".implode("&nbsp;", getXref($row['pid'])).": ".$row['annotation']."</a>";
        }

        while($row) {
                if (isset($row['scan'])) {
                    $mshtml = "{$row['file']}.{$row['scan']}";
                } else {
                    $mshtml = $row['msid'];
                }

                if ($row['nullMass']==0) {
                    $mshtml = "<a href=\"./spectrum/view_spectrum.php?msid={$row['msid']}&pep={$row['id']}\" target=\"_blank\">$mshtml</a>&nbsp;&nbsp;";
                }

//                $param['Mass spectrum'] = $mshtml;
//                $headers['Mass spectrum'] = 1;
                $ms[$row['msid']] ++;
                $msheader[$row['msid']] = $mshtml;

                $link = $row['link'];
                if (empty($link)) {
                        $param['Reference'] = $row['reference'];
                } else {
                        $param['Reference'] = "<a href=\"{$link}\" target=\"_blank\">{$row['reference']}</a>";
                }
                $headers['Reference'] = 1;

                $query = "SELECT value,peptideParameterType.name FROM peptideParameter,peptideParameterType WHERE peptide='{$row['id']}' AND peptideParameter.parameter=peptideParameterType.id";
                $res1 = mysql_query($query) or die("Error, query failed:$query");
                while($row1 = mysql_fetch_array($res1, MYSQL_ASSOC)) {
                    $param[$row1['name']] = $row1['value'];
                    $headers[$row1['name']] = 1;
                }

                $params[] = $param;
                
                $row = mysql_fetch_array($result, MYSQL_ASSOC);
        }

        // query for datasources
        $result = mysql_query($queryDs) or die('Error, query failed:'.$queryDs);
        while($row = mysql_fetch_array($result, MYSQL_ASSOC)) {
                $dataSource[$row['id']] = $row['reference'];
        }
        if (count($dataSource)>1) {
            $dataSource[0] = "All";
            ksort($dataSource);
        }

        echo "<table>";
        echo "<tr><td align=\"right\" width=\"100\"><b>NR Sequence:</b></td><td>&nbsp;</td><td>".$seq."</td></tr>";
        echo "<tr><td align=\"right\"><b>Organism:</b></td><td>&nbsp;</td><td><i>$orghtml</td></tr>";
        echo "<tr><td align=\"right\"><b>Protein:</b></td><td>&nbsp;</td><td>$prohtml</td></tr>";
        echo "<tr><td align=\"right\"><b>Location:</b></td><td>&nbsp;</td><td>".($loc+1)."</td></tr>";

        echo "<tr><td align=\"right\"><b>Reference:</b></td><td>&nbsp;</td><td>";
        echo "<form method=\"get\" action=\"peptide.php\">";
        if(isset($_GET['id'])) {
            echo "<input name=\"id\" type=\"hidden\" id=\"id\" value=\"{$_GET['id']}\" />";
	} elseif (isset($_GET['pnrseq'])) {
            echo "<input name=\"pnrseq\" type=\"hidden\" id=\"id\" value=\"$pseq\" />";
            echo "<input name=\"pro\" type=\"hidden\" id=\"id\" value=\"$pro\" />";
            echo "<input name=\"loc\" type=\"hidden\" id=\"id\" value=\"$loc\" />";
        }
        echo "<select name=\"ref\" size=\"1\">";
        foreach($dataSource as $dsId => $dsRef) {
                echo "<option value=\"$dsId\"";
                if ($ref==$dsId) {
                    echo "selected=\"selected\"";
                }
                echo ">$dsRef</option>";
        }
        echo "</select>";
        echo "<input name=\"select\" type=\"submit\" id=\"select\" value=\"Select\" /></form>";
        echo "</td></tr>";

//        $massLink = "<a href=\"./spectrum.php?id=".implode(',',$ms)."\">".count($ms)."</a>";
        $massLink = count($ms)."&nbsp;&nbsp;"
            ."<a href=\"#\" name=\"hide\" style=\"display: none\" onclick=\"toggleDisplay('show');toggleDisplay('hide');return false;\">hide</a>"
            ."<a href=\"#\" name=\"show\" style=\"display: show\" onclick=\"toggleDisplay('show');toggleDisplay('hide');return false;\">show</a>";
        echo "<tr><td align=\"right\"><b>No. of Spectra:</b></td><td>&nbsp;</td><td>$massLink</td></tr>";
        echo "</table>";
        echo "&nbsp;<br/>";

        echo "<table border=\"1\" name=\"hide\" style=\"display: none\">";
        echo "<tr>";
        echo "<td>Spectrum</td>";
        foreach ($headers as $h=>$tmp) {
            echo "<td>{$h}</td>";
        }
        echo "</tr>";
        
//        $param = current($params);
        $i = 0;
        foreach ($ms as $msid=>$mscount) {
            $mp = merge_params(array_slice($params, $i, $mscount));
            $i += $mscount;
            $nmp = count($mp);
            echo "<tr><td rowspan=\"$nmp\">{$msheader[$msid]}</td>";
            for($j = 0; $j<$nmp; $j++) {
                if ($j>0)
                    echo "<tr>";
                $param = $mp[$j];
                foreach ($headers as $h=>$tmp) {
                    echo "<td>{$param[$h]}</td>";
                }
                echo "</tr>";
            }
        }

        echo "</table>";

	include '../dbconfig/closedb.php';
?>
	
	

<?php getBottom(); ?>
